﻿using System.Collections;
using System;
using System.Collections.Generic;
using JZ.JiangSu.IRepository;
using JZ.JiangSu.Model.Entity;
using System.Linq;

namespace JZ.JiangSu.Repository
{
    public partial class UserRepository : BaseRepository<User>, IUserRepository
    {
        private readonly IUserInfoRepository _userInfoRepo = new UserInfoRepository();
        private readonly ICompanyInfoRepository _companyInfoRepo = new CompanyInfoRepository();
        /// <summary>
        /// 根据登录名获取用户信息
        /// </summary>
        /// <param name="loginName"></param>
        /// <returns></returns>
        public IList<User> GetUserByPhone(string loginName)
        {
            return GetEntities(string.Format("Phone='{0}'", loginName));
        }
        /// <summary>
        /// 根据ip和时间获取用户
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public int GetUserByIPinHoursCount(string ip)
        {
            return GetTotalCount(string.Format("ip='{2}' and SubTime between '{0}' and '{1}' ", DateTime.Now.AddHours(-1), DateTime.Now, ip));
        }
        public int ChangePwd(int id, string newPwd)
        {
            return Update(new List<int>() { id }, new Dictionary<string, object>()
           {
               {"pwd",newPwd}
           });
        }
        public int UpdateUserPhoneById(int userId, string phone)
        {
            return Update(new List<int>() { userId }, new Dictionary<string, object>()
            {
                {"Phone", phone}
            });
        }
        public int GetUserChildCount(int masterId)
        {
            var ht = new Hashtable {{"masterId", masterId}};
            return repository.QueryForObject("GetUserChildCount", ht);
        }
        public int UpdateUserIsMasterById(int[] userIds, bool isMaster, int masterId)
        {
            int result = isMaster ? 1 : 0;
            string fields = string.Format(" isMaster = {0} ", result);
            string whereCondition = string.Format(" id in ( {0} )", string.Join(",", userIds));
            int r1 = Update(fields, whereCondition);
            fields = string.Format(" MasterId = {0}", masterId);
            int r2 = Update(fields, whereCondition);
            return r1 + r2;
        }

        /// <summary> 企业主账号关联子账号时，子账号资料要与主账号同步 </summary>
        /// /// <param name="masterId">当前企业主账号ID</param>
        /// <returns></returns>
        public int UpdateChildInfoByMasterId(int masterId)
        {
            return repository.Update("UpdateChildInfoByMasterId", masterId);
        }


        public int GetUserSubAccountCount(int userId, bool isExcludeSelf, bool? subAccountType)
        {
            int r = 0;
            if (subAccountType != null)
            {
                r = subAccountType == true ? 1 : 0;
            }
            string whereCondition = string.Format(@" [MasterId]={0}{1}{2} and [Phone]!='del'",
                userId,
                isExcludeSelf ? " and [ID]!=" + userId : "",
                subAccountType == null ? "" : " and [IsCompany] =" + r);
            return GetTotalCount(whereCondition);
        }

        public List<User> GetUserInfoByMasterId(int start, int pageSize, int userId, bool isExcludeSelf, bool? subAccountType)
        {
            var r = 0;
            if (subAccountType != null)
            {
                r = subAccountType == true ? 1 : 0;
            }
            var whereCondition = string.Format(@" [MasterId]={0}{1}{2} and [Phone]!='del'",
                userId,
                isExcludeSelf ? " and [ID]!=" + userId : "",
                subAccountType == null ? "" : " and [IsCompany] =" + r);
            var ht = new Hashtable {{"start", start}, {"pageSize", pageSize}, {"whereCondition", whereCondition}};
            return repository.QueryForList("GetUserInfoByMasterId", ht).ToList();
        }

        public List<User> GetUserInfoByMasterIdWithInfo(int start, int pageSize, int userId, bool isExcludeSelf, bool? subAccountType)
        {
            var r = 0;
            if (subAccountType != null)
            {
                r = subAccountType == true ? 1 : 0;
            }
            var whereCondition = string.Format(@" [MasterId]={0}{1}{2} and [Phone]!='del'",
                userId,
                isExcludeSelf ? " and [ID]!=" + userId : "",
                subAccountType == null ? "" : " and [IsCompany] =" + r);
            var ht = new Hashtable { { "start", start }, { "pageSize", pageSize }, { "whereCondition", whereCondition } };
            return repository.QueryForList("GetUserInfoByMasterIdWithInfo", ht).ToList();
        }


        public List<User> GetUserInfoByMasterIdSech(int userId, bool isExcludeSelf, bool? subAccountType, string sechPhone)
        {
            var whereCondition = string.Format(@" [MasterId]={0}{1}{2}{3}",
                                    userId,
                                    isExcludeSelf ? " and [ID]!=" + userId : "",
                                    subAccountType == null ? "" :
                                    " and [IsCompany] ='" + subAccountType.Value + "'", " and [Phone] ='" + sechPhone + "'");
            //var ht = new Hashtable {{"whereCondition", whereCondition}};
            return repository.QueryForList("GetUserInfoByMasterIdSech", whereCondition).ToList();
        }


        public User GetCompanyInfoByName(string companyName)
        {
            var ht = new Hashtable {{"companyName", companyName}};
            return repository.QueryForList("GetCompanyInfoByName", ht).ToList().FirstOrDefault();
        }


        public List<User> GetUserListByMasterId(int userId)
        {
            var ht = new Hashtable {{"userId", userId}};
            return repository.QueryForList("GetUserListByMasterId", ht).ToList();

        }

        /// <summary>
        /// 分配简历列表搜索，以手机号进行搜索
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="phonenum"></param>
        /// <returns></returns>
        public List<User> GetUserListByPhoneSearchPayCoupon(int userId, string phonenum)
        {
            var ht = new Hashtable {{"userId", userId}, {"phoneNumber", phonenum}};
            return repository.QueryForList("GetUserListByPhoneSearchPayCoupon", ht).ToList();
        }

        /// <summary> 根据航母号ID查询飞机号集合 置顶券 </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public List<User> GetUserListByMasterIdOnTopCoupon(int userId)
        {
            var ht = new Hashtable {{"userId", userId}};
            return repository.QueryForList("GetUserListByMasterIdOnTopCoupon", ht).ToList();
        }


        public int UpdateTopCoupon(List<KeyValuePair<int, int>> list)
        {
            var arrId = new ArrayList();
            var sql = @"update [User] set TopCouponCount=TopCouponCount+
					case ID ";
            foreach (var t in list)
            {
                sql += " when " + t.Key + " then " + t.Value * 100;
                arrId.Add(t.Key);
            }
            sql += " end where ID in(" + string.Join(",", arrId.ToArray()) + ")";
            var ht = new Hashtable {{"sql", sql}};
            return repository.Update("executeUpdateSqlUser", ht);
        }

        /// <summary> 更新用户实体 </summary>
        /// <param name="user">参数：用户实体</param>
        /// <returns>受影响行数</returns>
        public int UpdateUserEntity(User user)
        {
            return Update(user);
        }

        public int AutoUpdateEntity(Hashtable ht)
        {
            return AutoUpdate(ht);
        }


        public User GetUserByResumeId(int resumeId)
        {
            return repository.QueryForList("GetUserByResumeId", new Hashtable() { { "resumeId", resumeId } }).FirstOrDefault();
        }
        /// <summary> 给指定用户分配指定的权限 </summary>
        /// <param name="userId">用户Id</param>
        /// <param name="power">权限</param>
        /// <returns></returns>
        public int UpdateUserPermissionByUserId(int userId, int power)
        {
            return Update(string.Format("[Permission] ={0}",power),string.Format("id={0}",userId));
            //string cmdStr = @"update [User] set [Permission] =@power where [ID] =@userId";
            //return Tools.SqlHelperForCache.GetResultCount(ConnStr, cmdStr, new[]
            //{
            //    new SqlParameter("@power", power),
            //    new SqlParameter("@userId", userId)
            //});
        }
    }
}
